﻿namespace MobileTrack.Web.ActionFilters
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using MobileTrack.Core;

    [ExcludeFromCodeCoverage]
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public sealed class ChangePasswordRedirectActionFilterAttribute : ActionFilterAttribute
    {
        private const string AccountController = "Account";

        private const string ChangePasswordAction = "ChangePassword";

        private const string LogOffAction = "LogOff";

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext != null
                && HttpContext.Current.User.Identity.IsAuthenticated
                && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals(AccountController, StringComparison.OrdinalIgnoreCase)
                && (!filterContext.ActionDescriptor.ActionName.Equals(ChangePasswordAction, StringComparison.OrdinalIgnoreCase) || !filterContext.ActionDescriptor.ActionName.Equals(LogOffAction, StringComparison.OrdinalIgnoreCase)))
            {
                var profile = HttpContext.Current.Profile as MobileTrackProfile;
                if ((profile != null) && !profile.Initialized)
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary
                        {
                            { "controller", AccountController },
                            { "action", ChangePasswordAction }
                        });
                }
            }
        }
    }
}